Web Streams API
queueを使ってchunk化されたデータを処理する
3種類Streamを繋いで使う
ReadableStream
TranformStream
WritableStream
参考
An Introduction to Streaming on the Web – Vercel
Vercelによるわかりやすい解説
#WIP
https://developer.mozilla.org/ja/docs/Web/API/Streams_API
https://jxck.hatenablog.com/entry/whatwg-stream
https://sbfl.net/blog/2018/05/26/javascript-streams-api/
https://nodejs.org/api/webstreams.html#web-streams-api
https://streams.spec.whatwg.org/
An Introduction to Streaming on the Web – Vercel
Vercelによる解説
https://gyazo.com/6e0a365bb63f6f2ef0001d0147596507
code:例.ts
const decoder = new TextDecoder();
const encoder = new TextEncoder();
const readableStream = new ReadableStream({
start(controller) {
const text = "Stream me!";
controller.enqueue(encoder.encode(text)); // queueにいれる
controller.close();
},
});
const transformStream = new TransformStream({
transform(chunk, controller) {
// データを取り出して、変換して、再度queueにいれる
const text = decoder.decode(chunk);
controller.enqueue(encoder.encode(text.toUpperCase()));
},
});
const writableStream = new WritableStream({
write(chunk) {
console.log(decoder.decode(chunk)); // 取り出す
},
});
// 呼び出す
// pipeThrough, pipeToを使う
readableStream
.pipeThrough(transformStream)
.pipeTo(writableStream); // STREAM ME!
Web Streamはフロー制御を通じてBackpressureを処理する
https://vercel.com/blog/an-introduction-to-streaming-on-the-web#handling-backpressure-with-web-streams
queueが増えてくるとBackpressure状態にして、producerの生成を遅らせる